package com.gzw.scm.activity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import com.google.gson.reflect.TypeToken;
import com.gzw.scm.R;
import com.gzw.scm.adapter.WBAdapter;
import com.gzw.scm.base.BaseActivity;
import com.gzw.scm.bean.Constant;
import com.gzw.scm.bean.DBSQInfo;
import com.gzw.scm.utils.HttpUtils;
import com.gzw.scm.utils.JsonUtil;
import com.gzw.scm.utils.UrlUtils;
import com.gzw.scm.view.SwipeRefreshLayout;
import org.apache.log4j.Logger;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2017/5/23.
 */

public class SelectWBXXActivity extends BaseActivity implements SwipeRefreshLayout.OnRefreshListener{
    private Context mContext;
    private RecyclerView mRecyclerView;
    private Toolbar toolbar;
    private SwipeRefreshLayout mSwipeLayout;
    private WBAdapter wbAdapter;
    private Intent intent;
    private String type;
    private List<DBSQInfo> ls_all;
    private Logger log;
    private RefreshOrLoad refreshOrLoad = RefreshOrLoad.REFRESH;
    enum RefreshOrLoad {
        REFRESH, LOAD
    }

    @Override
    protected void setContentView() {
        setContentView(R.layout.activity_qqjg);
    }

    @Override
    protected void initViews() {
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        mRecyclerView = (RecyclerView) findViewById(R.id.rv_jg);
        //初始化 log
        log=Logger.getLogger(this.getClass());
    }

    @Override
    protected void initData() {
        mContext = this;

        intent=getIntent();
        type=intent.getStringExtra("type");

        if(type.equals("0")){
            toolbar.setTitle("选择发出部门");
        }else{
            toolbar.setTitle("选择申请部门");
        }
        setSupportActionBar(toolbar);

        ls_all=new ArrayList<>();

        mRecyclerView.setHasFixedSize(true);
        //设置布局管理器
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        //设置Item增加、移除动画
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());

        //添加默认分割线
        mSwipeLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_container);
        mSwipeLayout.setColor(android.R.color.holo_blue_bright,
                android.R.color.holo_green_light,
                android.R.color.holo_orange_light,
                android.R.color.holo_red_light);
        mSwipeLayout.setOnRefreshListener(this);
        mSwipeLayout.setMode(SwipeRefreshLayout.Mode.PULL_FROM_START);
        mSwipeLayout.setLoadNoFull(false);

        if(type.equals("0")){
            DBJSTask getTask = new DBJSTask();
            getTask.execute();
        }else{
            DBFCTask getTask = new DBFCTask();
            getTask.execute();
        }

    }

    @Override
    protected void initEvents() {
        toolbar.setNavigationOnClickListener( v -> finish());
    }

    @Override
    public void onRefresh() {
        refreshOrLoad = RefreshOrLoad.REFRESH;
        if(type.equals("1")){
            DBFCTask getTask = new DBFCTask();
            getTask.execute();
        }else{
            DBJSTask getTask = new DBJSTask();
            getTask.execute();
        }
    }

    /*由上一界面返回是进行的操作*/
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        //普通签收
        if (resultCode == 1) {
            type="1";
            onRefresh();
        }else if(resultCode == 0){
            type="0";
            onRefresh();
        }
    }

    /**
     * 获取周转箱调拨发出的部门和数量数据请求
     */
    public class DBFCTask extends AsyncTask<String, Void, String> {
        @Override
        protected void onPreExecute() {
            if (refreshOrLoad == RefreshOrLoad.REFRESH) {
                mSwipeLayout.setRefreshing(true);
            }
        }
        protected String doInBackground(String... params) {
            SharedPreferences sharedPreferences = getSharedPreferences(Constant.USERINFO_KEY, Context.MODE_PRIVATE);
            int did = sharedPreferences.getInt(Constant.DID_KEY, 0);
            String url ="did="+did;
            return HttpUtils.doPost(UrlUtils.getInstance().getNewJavaUrl("pda_apply.do","getApply"), url);
        }

        @Override
        protected void onPostExecute(final String result) {
            //{"result":"true","value":"1,张三,13075333333,20,2,李四,13333333333,30"}
            if (refreshOrLoad == RefreshOrLoad.REFRESH) {
                mSwipeLayout.setRefreshing(false);
            }
            try {

            if (result == null || result.length() == 0) {
                showAlertDialog("连接异常");
                return;
            }
                if(result.contains("系统异常")){
                    showAlertDialog("网络异常");
                    return;
                }
            if(result.contains("apply")){
                String info = JsonUtil.getMsg(result,"apply").toString();
                List<DBSQInfo> ls_info = JsonUtil.getPersons(info, new TypeToken<List<DBSQInfo>>() {
                }.getType());
                if(ls_info.size()==0){
                    showAlertDialog("暂无调拨申请信息");
                }
                ls_all.clear();
                ls_all.addAll(ls_info);

                if (wbAdapter == null) {
                    mRecyclerView.setAdapter(wbAdapter = new WBAdapter(ls_all,"1"));
                } else {
                    wbAdapter.notifyDataSetChanged();
                }

                wbAdapter.setOnRecyclerViewListener(position ->  {
                        Intent intent = new Intent(mContext, WBZZXActivity.class);
                        intent.putExtra("type","1");
                        DBSQInfo dbsqInfo = ls_all.get(position);
                        Bundle bundle = new Bundle();
                        bundle.putSerializable("dbsqInfo",dbsqInfo);
                        intent.putExtras(bundle);
                        startActivityForResult(intent, 1);
                });
            }
            }catch (Exception e) {
                log.info("OutTboxs:"+e.toString()+"/result="+result);
                e.printStackTrace();
                showAlertDialog(e.toString());
            }
            }
    }

    /**
     * 获取调拨接收部门和数量数据请求
     */
    public class DBJSTask extends AsyncTask<String, Void, String> {
        @Override
        protected void onPreExecute() {
            if (refreshOrLoad == RefreshOrLoad.REFRESH) {
                mSwipeLayout.setRefreshing(true);
            }
        }
        protected String doInBackground(String... params) {
            SharedPreferences sharedPreferences = getSharedPreferences(Constant.USERINFO_KEY, Context.MODE_PRIVATE);
            int did = sharedPreferences.getInt(Constant.DID_KEY, 0);
            String url ="did="+did;
            return HttpUtils.doPost(UrlUtils.getInstance().getNewJavaUrl("pda_apply.do","getStayApply"), url);
        }

        @Override
        protected void onPostExecute(final String result) {
            if (refreshOrLoad == RefreshOrLoad.REFRESH) {
                mSwipeLayout.setRefreshing(false);
            }
            try{
            if (result == null || result.length() == 0) {
                showAlertDialog("连接异常");
                return;
            }
                if(result.contains("系统异常")){
                    showAlertDialog("网络异常");
                    return;
                }
            if(result.contains("stay")){
                String info = JsonUtil.getMsg(result,"stay").toString();
                List<DBSQInfo> ls_info = JsonUtil.getPersons(info, new TypeToken<List<DBSQInfo>>() {
                }.getType());
                if(ls_info.size()==0){
                    showAlertDialog("暂无调拨申请信息");
                }
                ls_all.clear();
                ls_all.addAll(ls_info);

                if (wbAdapter == null) {
                    mRecyclerView.setAdapter(wbAdapter = new WBAdapter(ls_all,"0"));
                } else {
                    wbAdapter.notifyDataSetChanged();
                }

                wbAdapter.setOnRecyclerViewListener(position ->  {
                    Intent intent = new Intent(mContext, WBZZXActivity.class);
                    intent.putExtra("type","0");
                    DBSQInfo dbsqInfo = ls_all.get(position);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("dbsqInfo",dbsqInfo);
                    intent.putExtras(bundle);
                    startActivityForResult(intent, 1);
                });
            }
            }catch (Exception e) {
                log.info("getApply:"+e.toString()+"/result="+result);
                e.printStackTrace();
                showAlertDialog(e.toString());
            }
        }
    }

}